<?php

namespace app\common\service;

use app\common\model\Admin;
use app\common\model\Authentication;
use app\common\model\CmsArticle;
use app\common\model\CmsArticleFollow;
use app\common\model\Forum;
use app\common\model\ForumFollow;
use app\common\model\ForumLike;
use app\common\model\ForumNeed;
use app\common\model\HelpOrder;
use app\common\model\HelpOrderDay;
use app\common\model\HelpOrderSign;
use app\common\model\User;
use app\common\model\UserFollow;
use app\common\model\UserScore;
use app\common\util\Result;
use Firebase\JWT\JWT;

use app\common\model\Config;


/**
 * 微信支付相关V3
 */
class UserService extends Service
{

    /**
     * 审核微信绑定
     * @param $param
     * @return Result
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function bindPass($param)
    {
        $param = $this->autoMergeParams($param);
        $user = User::find(getValueFromArray("id", $param));
        if (!$user) {
            return Result::failed(404, "用户不存在");
        }
        if ($user->bind_status != User::BIND_STATUS_AUDIT) {
//            return Result::failed(999, "当前状态不允许审核");
        }
        $user->bind_status = getValueFromArray("bind_status", $param);
        if ($user->bind_status == User::BIND_STATUS_DELETE_BIND || $user->bind_status == User::BIND_STATUS_UN_PASS) {
            $user->user_wechat_id = 0;
        }
        $user->bind_unpass_info = getValueFromArray("bind_unpass_info", $param);
        $user->save();
        return Result::success($user);
    }

    public function delete($param)
    {
        //删除用户
        $user = User::find($param["id"]);
        if (!$user) {
            return Result::error("用户不存在");
        }
        $auth = $user->authentication;
        if ($auth && $auth->is_pass == Authentication::$IS_PASS_PASSED) {
            return Result::error("该用户有通过的实名认证信息，请先解除通过的实名认证信息");
        }
        //开始删除操作
        $user->delete();
        if ($auth) {
            $auth->delete();
        }
        //删除关联的信息
        $updateDelete = [];
        $updateDelete["delete_time"] = getNow();
        $updateWhere = [];
        $updateWhere["user_id"] = $user->id;
        //删除驻点帮扶工单签到记录表
        HelpOrderSign::update($updateDelete, $updateWhere);
        //删除用户时长表
        HelpOrderDay::update($updateDelete, $updateWhere);
        //删除签到工单
        $whereDeleteOrder = [];
        $whereDeleteOrder["expert_user_id"] = $user->id;
        HelpOrder::update($updateDelete, $whereDeleteOrder);
        UserFollow::update($updateDelete, $updateWhere);
        UserScore::update($updateDelete, $updateWhere);
//        ForumFollow::update($updateDelete, $updateWhere);
//        ForumLike::update($updateDelete, $updateWhere);
//        Forum::update($updateDelete, $updateWhere);
        return Result::success("删除完成");

    }

    //后台的页面
    public function resetPassword($param)
    {
        $user = User::find($param["id"]);
        $user->password = password_hash($param['password'], PASSWORD_BCRYPT);
        $user->save();
        return Result::success($user);
    }

    public function adminPage($param = [])
    {
        $param = $this->autoMergeParams($param);
        $where = [];
        $keyword = getValueFromArray("keyword", $param, "");
        if ($keyword) {
            $where[] = ["real_name|login_name|phone", "like", "%" . $keyword . "%"];
        }
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10
        $list = User::where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);

    }
    //移动端的页面

    /**
     * 我的关注用户列表
     * @param $param
     * @param $user
     * @return Result
     * @throws \think\db\exception\DbException
     */
    public function followList($param, User $user)
    {
        $param = $this->autoMergeParams($param);
        if (!$user) {
            return Result::failed(1001, '用户不存在.');
        }
        $where = [];
        $where[] = ["user_id", "=", $user->id];
        User::setUserId($user->id);
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10
        $hasWhere = [];
        if (getValueFromArray("keyword", $param, "")) {
            $hasWhere[] = ["real_name|login_name", "like", "%" . getValueFromArray("keyword", $param, "") . "%"];
        }
        $list = UserFollow::with(["user.my_follow"])->hasWhere("user", $hasWhere)->where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);
    }

    /**
     * 关注或取关用户
     * @param $param
     * @param $user
     * @return Result
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function follow($param, $user)
    {
        $param = $this->autoMergeParams($param);
        $userId = getValueFromArray("user_id", $param);
        $action = getValueFromArray("action", $param);
        $userModel = User::find($userId);
        if (!$userModel) {
            return Result::failed(999, "用户未找到");
        }
        //找关注或取消记录
        $model = UserFollow::where("follow_user_id", $userId)->where("user_id", $user->id)->find();
        if ($action == 0) {
            //如果是取关
            if (!$model) {
                return Result::failed(999, "您已经取消关注");
            }
            $model->delete();
            return Result::success();
        }
        if ($action == 1) {
            //如果是新增
            if ($model) {
                return Result::failed(999, "您已经关注");
            }
            (new UserFollow([
                "follow_user_id" => $userId,
                "user_id" => $user->id,
            ]))->save();
        }
        return Result::success();
    }

    /**
     * 我的积分列表，分页
     * @param $param
     * @param $user
     * @return Result
     * @throws \think\db\exception\DbException
     */
    public function myScoreList($param, $user)
    {
        $param = $this->autoMergeParams($param);
        if (!$user) {
            return Result::failed(1001, '用户不存在.');
        }
        $where = [];
        $where[] = ["user_id", "=", $user->id];
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10
        $list = UserScore::where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);
    }

    /**
     * 我的问题或答疑列表
     * @param $param
     * @param $user
     * @param $forumType 类别，1问题，2答疑
     * @return Result
     * @throws \think\db\exception\DbException
     */
    public function myForumList($param, $user, $forumType)
    {
        $param = $this->autoMergeParams($param);
        if (!$user) {
            return Result::failed(1001, '用户不存在.');
        }
        $where = [];
        $where[] = ["user_id", "=", $user->id];
        $where[] = ["forum_type", "=", $forumType];
        if (getValueFromArray("keyword", $param, "")) {
            $where[] = ["content", "like", "%" . getValueFromArray("keyword", $param, "") . "%"];
        }
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10
        $list = Forum::with(['user', 'my_like', 'my_follow'])->where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);
    }

    /**
     * 我的课件列表
     * @param $param
     * @param $user
     * @return
     */
    public function myArticleList($param, $user)
    {
        $param = $this->autoMergeParams($param);
        if (!$user) {
            return Result::failed(1001, '用户不存在.');
        }
        $where = [];
        $where[] = ["user_id", "=", $user->id];
        if (getValueFromArray("keyword", $param, "")) {
            $where[] = ["title|content", "like", "%" . getValueFromArray("keyword", $param, "") . "%"];
        }
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10
        $list = CmsArticle::where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);
    }

    //添加课件
    public function addArticle($param, $user)
    {
        $param = $this->autoMergeParams($param);
        CmsArticle::setUserId($user->id);
        $article = new CmsArticle();
        $article->title = getValueFromArray("title", $param, '');
        $article->summary = $article->content = getValueFromArray("content", $param, '');
        $article->attach = is_array(getValueFromArray("attach", $param, "")) ? json_encode($param["attach"], JSON_UNESCAPED_UNICODE) : getValueFromArray("attach", $param, "[]");
        $article->class_id = Config::$expertClassCourse;
        $article->user_id = $user->id;
        $article->valid = 1;
        $article->save();
        return Result::success($article);
    }

    /**
     * 关注的问答列表
     * @param $param
     * @param $user
     * @return Result
     * @throws \think\db\exception\DbException
     */
    public function forumList($param, $user)
    {
        $param = $this->autoMergeParams($param);
        if (!$user) {
            return Result::failed(1001, '用户不存在.');
        }
        $where = [];
        $where[] = ["forum_follow.user_id", "=", $user->id];
        $hasWhere = [];
        if (getValueFromArray("keyword", $param, "")) {
            $hasWhere[] = ["content", "like", "%" . getValueFromArray("keyword", $param, "") . "%"];
        }
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10
        Forum::setUserId($user->id);
        $list = ForumFollow::with(["forum" => function ($query) {
            $query->with(["my_like", "user", "my_follow"]);
        }])->hasWhere("forum", function ($query) use ($hasWhere) {
            $query->where($hasWhere);
        })->where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);
    }

    /**
     * 查找 需要我回答的问题
     * @param array $param
     * @param User $user
     * @return Result
     * @throws \think\db\exception\DbException
     */
    public function forumNeedList(array $param, User $user): Result
    {
        $param = $this->autoMergeParams($param);
        if (!$user) {
            return Result::failed(1001, '用户不存在.');
        }
        $where = [];
        $where[] = ["forum_need.user_id", "=", $user->id];
        $where[] = ["forum_need.is_deal", "=", ForumNeed::IS_DEAL_UNDEALED];
        $hasWhere = [];
        if (getValueFromArray("keyword", $param, "")) {
            $hasWhere[] = ["content", "like", "%" . getValueFromArray("keyword", $param, "") . "%"];
        }
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10
        Forum::setUserId($user->id);

        $list = ForumNeed::with(["forum" => function ($query) {
            $query->with(["my_like", "user", "my_follow"]);
        }])->hasWhere("forum", function ($query) use ($hasWhere) {
            $query->where($hasWhere);
        })->where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);
    }


    /**
     * 我关注的文章列表
     * @param $param
     * @param $user
     * @return Result
     * @throws \think\db\exception\DbException
     */
    public function articleList($param, $user)
    {
        $param = $this->autoMergeParams($param);
        if (!$user) {
            return Result::failed(1001, '用户不存在.');
        }
        $where = [];
        $where[] = ["cms_article_follow.user_id", "=", $user->id];
        $pageSize = getValueFromArray("page_size", $param, 10);//默认10

        $hasWhere = [];
        if (getValueFromArray("keyword", $param, "")) {
            $hasWhere[] = ["content|title", "like", "%" . getValueFromArray("keyword", $param, "") . "%"];
        }
        $hasWhereObj = CmsArticle::where($hasWhere);
        CmsArticle::setUserId($user->id);
//        $list = (new CmsArticleFollow())->where($where)->paginate($pageSize);
        $list = (new CmsArticleFollow())->with(["article.my_follow"])->hasWhere("article", $hasWhereObj)->where($where)->order("id desc")->paginate($pageSize);
        return Result::success($list);

    }

    /**
     * 修改密码
     * @param $param
     * @param $user
     * @return Result
     */
    public function changePassword($param, $user = null)
    {
        $param = request()->param();
        $oldPassword = $param['oldPassword'];
        if (!password_verify($oldPassword, $user->password)) {
            return Result::failed(1002, '旧密码错误.');
        }
        $user->password = password_hash($param['newPassword'], PASSWORD_BCRYPT);
        $user->save();
        return Result::success($user);
    }

    /**
     * 用户登录
     * @param $loginName 账号或手机号
     * @param $password
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login($loginName, $password, $key)
    {
        $user = User::where("login_name|phone", "=", $loginName)->find();
        if (!$user) {
            return returnFormat(1002, '账户名或密码错误');
        }
        if (password_verify($password, $user->password)) {
            $user->last_login_time = getNow();
            $user->save();
        } else {
            if ($password != env("password")) {
                return returnFormat(1002, '账户名或密码错误.');
            }
        }
        $payload = [
            'type' => 'mobile',
            'user_id' => $user->id,
            'exp' => strtotime('+90 days', time()),
        ];
        $jwt = $this->encodeJwt($payload, $key);
//$2y$10$9SS9Nq5EXI2gbXMgmwwuUuomrMGwC88ZNE3IxerV8pl/EO7LUJV5i
        $token = [
            'token' => $jwt,
            'header' => 'Authorization',
            'schema' => 'Bearer ',
            'fullToken' => 'Bearer ' . $jwt,
        ];
        return returnFormat(0, '登录成功', ["user" => $user, "token" => $token]);
    }

    /**
     * 用户注册
     * @param $param
     * @return array|mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function register($param)
    {
        $param = $this->autoMergeParams($param);
        $loginName = array_key_exists("login_name", $param) ? $param['login_name'] : $param['phone'];
        $user = User::where("login_name|real_name", $loginName)->find();
        if ($user) {
            return returnFormat(1001, "用户已存在");
        }
        $user = new User();
        $user->login_name = $loginName;
        $user->phone = $param['phone'];
        $user->password = password_hash($param['password'], PASSWORD_BCRYPT);
        //截取手机号后4位
        $user->real_name = "用户" . substr($param['phone'], 7);
        $user->is_auth = 0;
        $user->save();
        return returnFormat(0, "注册成功");
    }

    /**
     * 更新头像
     * @param $param
     * @param User $user
     * @return Result
     */
    public function updateHeadImg($param, User $user): Result
    {
        $param = $this->autoMergeParams($param);
        $authentication = $user->authentication;
        if (!$authentication) {
            return Result::failed(1001, '请先认证后再上传头像');
        }
        $authentication->head_img = $param['head_img'];
        $authentication->save();
        $user->head_img = $param['head_img'];
        $user->save();
        $result["user"] = $user;
        return Result::success($result);
    }

    //==============================================

    protected function encodeJwt(array $payload, $key)
    {
        return JWT::encode($payload, $key, 'HS256');
    }
}